﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Drive.Support.Extensions
{
    public static class IdConvExtension
    {
        private static String str62keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        public static String IntToEnode62(this Int64 int10)
        {
            string s62 = "";
            int r = 0;
            while (int10 != 0)
            {
                r = Convert.ToInt32(int10 % 62);
                s62 = str62keys[r] + s62;
                int10 = (Int64)Math.Floor(int10 / 62.0);
            }
            return s62;
        }

        public static Int64 Encode62ToInt(this String str62)
        {
            Int64 i10 = 0;
            for (var i = 0; i < str62.Length; i++)
            {
                double n = str62.Length - i - 1;
                i10 += Convert.ToInt64(str62keys.IndexOf(str62[i]) * Math.Pow(62, n));
            }
            return i10;
        }

        public static string Mid2Id(this string str62) //yvr29p8dG
        {
            String id = "";
            for (int i = str62.Length - 4; i > -4; i = i - 4) //从最后往前以4字节为一组读取字符
            {
                int offset = i < 0 ? 0 : i;
                int len = i < 0 ? str62.Length % 4 : 4;
                String str = Encode62ToInt(str62.Substring(offset, len)).ToString();

                if (offset > 0) str = str.PadLeft(7, '0'); //若不是第一组，则不足7位补0

                id = str + id;
            }
            return id;
        }

        public static string Id2Mid(this string str10) //3474920895989800
        {
            string mid = "";
            for (int i = str10.Length - 7; i > -7; i = i - 7) //从最后往前以7字节为一组读取字符
            {
                int offset = i < 0 ? 0 : i;
                int len = i < 0 ? str10.Length % 7 : 7;
                var str = IntToEnode62(Convert.ToInt64(str10.Substring(offset, len)));
                mid = str + mid;
            }
            return mid;
        }
    }
}
